// +----------------------------------------------------------------------
// | BossHongshi [鸿时互娱管理系统]
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://www.hongshihuyu.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: wgh
// +----------------------------------------------------------------------
const fly=require("flyio")
module.exports = class extends think.cmswing.center {
  async __before() {
    await super.__before();
    // 判断是否登陆
    // await this.weblogin();
    if (!this.is_login) {
      // 判断浏览客户端
      if (this.isMobile) {
        // 手机端直接跳转到登录页面
        return this.redirect('/center/public/login');
      } else {
        return this.redirect('/cmswing/error/login');
      }
    }
  }
  
  // 密保房间
  async indexAction() {
		const opt = this.para('opt') || 1;
		console.log('opt-1:'+this.para('opt'));
		console.log('page-1:'+this.para('page'));
		console.log('page-2:'+this.get('page'));
    const userInfo = await this.model('member').find(this.user.uid);
    
//    var dd = new Date();
//    console.log('SAFEBOX_DELAY   -:'+this.config('setup.SAFEBOX_DELAY'));
//    var day2 = dd.valueOf()+(Number(this.config('setup.SAFEBOX_DELAY')) * 60000);
//    dd.setDate(dd.getDate() + 1);// 获取AddDayCount天后的日期
//    console.log('day2   -:'+day2);
//    console.log('dd.valueOf()  +1 -:'+dd.valueOf());
    
    let map;
    if (opt == 1) { // 存入
      map = {
    	catalog:1,
        pid:this.user.uid,
  	    proxy_id:userInfo.proxy_id
      };
    } else if (opt == 2) { // 取出
      map = {
    	catalog:2,
        pid:this.user.uid,
    	proxy_id:userInfo.proxy_id
      };
    }
    console.log('page-:'+this.para('page'));
    

    const data = await this.model('safebox').where(map).page(this.para('page')).order('create_time DESC').countSelect();
    for (const v of data.data) {
		  console.log('v.create_time------:');
					v.create_time = this.moment(v.create_time).format('YYYY-MM-DD HH:mm:ss');
    }
    const html = this.pagination(data);
    this.assign('pagination', html);
    console.log('count-:'+data.count);
    this.assign('count', data.count);
    
    this.assign('list', data.data);
    this.assign('opt',opt);
    
    this.meta_title = '密保房间';
    // 判断浏览客户端
    if (this.isMobile) {
      if (this.isAjax('get')) {
        return this.json(data);
      } else {
        this.active = 'center/index';
        return this.display(this.mtpl());
      }
    } else {
      return this.display();
    }
  }

//代理信息
  async infoAction() {
	
		const id = this.para('id') || null;
	    // 筛选
	    const agentInfo = await this.model('member').find(id);
	    this.assign('agentInfo', agentInfo);

	    // 直属代理统计
	    const lowernum = await this.model('member').where({
	    	is_admin:0,
	    	ia_uname:agentInfo.proxy_id
	    }).count('id');
	    this.assign('loweranum', lowernum);
	    
	    const url='http://47.97.119.70:5166/GameSupport/dn?cmd=getPlayers&agentId='+agentInfo.proxy_id+'&sign=password';
		  
	    fly.config.timeout=10000;
		fly.config.parseJson=true;
		  
		let ret = await fly.get(url);
		let playerdata = JSON.parse(ret.data);
		this.assign('lowerpnum', null!=playerdata?playerdata.data.arr.length:0);
	    
	    this.meta_title = '代理信息';
	    // 判断浏览客户端
	    if (this.isMobile) {
	      if (this.isAjax('get')) {
	        return this.json(data);
	      } else {
	        this.active = 'center/agent/index';
	        return this.display(this.mtpl());
	      }
	    } else {
	      return this.display();
	    }
  }
  
//代理信息
  async getcoinnumAction() {
	
		const roomno = this.para('roomno') || null;
		if (think.isEmpty(roomno)) {
		       return this.fail('房间号不能为空！');
		} 
		
		const sbdata = await this.model('safebox').where({password:roomno,pid:this.user.uid,status:1,type:1,catalog:1}).find();
		if (think.isEmpty(sbdata)) {
		       return this.fail('房间号不能存在！');
		}else{
			const mures = await this.model('member').where({id:this.user.uid}).increment('coin_count', sbdata.deposit_count);
			if(think.isEmpty(mures)){
			   return this.fail('领取失败！');
			}else{
				const sbres = await this.model('safebox').where({id:sbdata.id,password:roomno}).update({status:2});
				if(think.isEmpty(sbres)){
					return this.fail('领取失败！');
				}
			}
		}
		// 判断浏览客户端
	    if (this.isMobile) {
	      if (this.isAjax('get')) {
	    	  sbdata.status = 2;
		      return this.success(sbdata);
	      } else {
	        this.active = 'center/safebox/index';
	        return this.display(this.mtpl());
	      }
	    } else {
	      return this.display();
	    }
  }
  
//创建房间
  async createroomAction() {
	    const catalog = this.get('catalog') || '';
	    const userId = this.get('userId') || '';
	    const coinnum = this.get('coinnum') || '';
	    
	    const userInfo = await this.model('member').find(this.user.uid);
	    
	    var safeboxdata={};
        safeboxdata.pid=this.user.uid;
        safeboxdata.proxy_id = userInfo.proxy_id;
        safeboxdata.type = '1';
	    safeboxdata.catalog =catalog;
		safeboxdata.deposit_count = 0;
        safeboxdata.uid = userId;
        
        var dd = new Date();
        console.log('SAFEBOX_DELAY   -:'+this.config('setup.SAFEBOX_DELAY'));
        var day2 = dd.valueOf()+(Number(this.config('setup.SAFEBOX_DELAY')) * 60000);
        safeboxdata.create_time = dd.valueOf();
        //dd.setDate(dd.getDate() + 1);// 获取AddDayCount天后的日期
        console.log('day2   -:'+day2);
        console.log('dd.valueOf()  +1 -:'+dd.valueOf());
        safeboxdata.exp_time =day2;
        
//        const timestr = new Date().getTime().toString();
	    var roomno = '';
	    //http://hongshihuyu.com:5166/GameSupport/dn?cmd=createSafe&uid=28&sign=password
	    //http://127.0.0.1:5166/GameSupport/dn?cmd=createSafe&agentId=1&uid=28&sign=password
	    const url='http://hongshihuyu.com:5166/GameSupport/dn?cmd=createSafe&agentId='+userInfo.proxy_id+'&uid='+userId+'&sign=password';
	    fly.config.timeout=10000;
		fly.config.parseJson=true;
		fly.interceptors.response.use(
			    (response) => {
			        //只将请求结果的data字段返回
			        return response.data
			    },
			    (err) => {
			        //发生网络错误后会走到这里
			        //return Promise.resolve("ssss")
			    }
		)
	    let ret = await fly.get(url).catch(() => false);
		//let ret = await fly.get(url);
		console.log('ret----------------111--:'+ret);
	    let retjson = (ret === false?null:JSON.parse(ret));
		console.log("retjson--:"+JSON.stringify(retjson));
		
		if(!think.isEmpty(retjson.data)){
			if(!think.isEmpty(retjson.data.info)){
				roomno = retjson.data.info.roomId;
			}else{
			   return this.fail('添加失败！');
			}
		}else{
			return this.fail('添加失败！');
		}
		
		console.log("roomno--------------:"+roomno);
		
        safeboxdata.password = roomno;
        
	    // 创建房间
	    if(catalog == '2'){
	    	safeboxdata.deposit_count = coinnum;
	    	const mdres = await this.model('member').where({id:this.user.uid}).decrement('coin_count', coinnum);
			if(think.isEmpty(mdres)){
			   return this.fail('添加失败！');
			}
	    }
	    
        const res = await this.model('safebox').add(safeboxdata);
        if(think.isEmpty(res)){
        	const mires = await this.model('member').where({id:this.user.uid}).increment('coin_count',coinnum);
			return this.fail('添加失败！');
		}
        
				// safeboxdata.createtime = times(safeboxdata.create_time);
		safeboxdata.createtime = this.moment(safeboxdata.create_time).format('YYYY-MM-DD HH:mm:ss');
        
        if (res) {
        	// 判断浏览客户端
    	    if (this.isMobile) {
    	      if (this.isAjax('get')) {
    	        return this.success(safeboxdata);
    	      } else {
    	        this.active = 'safebox/index';
    	        return this.display(this.mtpl());
    	      }
    	    } else {
    	      return this.display();
    	    }
        } else {
        	return this.fail('添加失败！');
        }
	    
  }
  
};
